import http from "http";
import express from "express";
import { Server } from "socket.io";
import user from "./router/user.js";
const app = express();
const server = http.createServer(app);

app.use(express.static("public"));
/**
 * 全局接口监听
 */
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Credentials", true);
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, token, authorization"
  );
  res.header("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST, OPTIONS");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

/**
 * @description 定义接口请求
 */
app.get("/", () => {
  console.log("hello");
});

/**
 * 合并路由
 */
app.use("/user", user);

const io = new Server(server, {
  cors: {
    origin: "*",
  },
});

/**
 * @description socket.io 监听客户端连接
 * @method emit 对当前的client发送消息
 * @method emit 对某些client发送消息
 * @method broadcast.emit 对socket中其他用户发送消息(除了自己)
 */
const userList = [];
const socketList = {};
io.on("connection", (socket) => {
  /**
   * @description 新用户连接成功后, 可以获取到传递的参数，包括用户唯一标识
   */
  const { userId, userName } = socket.handshake.query;
  console.log(userName + " 连接成功");
  const userInfo = {
    userId,
    userName,
  };
  // 添加用户和连接数
  userList.push(userInfo);
  socketList[userId] = socket;
  socket.emit("connection");
  // 广播消息通知其他人
  socket.broadcast.emit("message", {
    type: "addUser",
    message: userInfo,
  });
  // 对当前用户发送用户列表
  socket.emit("message", {
    type: "userList",
    message: userList,
  });

  /**
   * @description 监听客户端发送的消息
   */
  socket.on("message", (data) => {
    if (data.type === "chatMessage") {
      // 广播消息通知其他人
      socket.broadcast.emit("message", {
        type: "chatMessage",
        message: data.message,
      });
    } else if (data.type === "singleMessage") {
      // 单聊
      data.message.toUserId.forEach((userId) => {
        socketList[userId].emit("message", {
          type: "chatMessage",
          message: data.message,
        });
      });
    }
  });

  /**
   *  @description 监听用户断开连接
   */
  socket.on("disconnect", () => {
    console.log(userId + "断开连接");
    // 删除用户和连接数
    userList.splice(userList.indexOf(userInfo), 1);
    // 广播消息通知其他人
    socket.broadcast.emit("message", {
      type: "delUser",
      message: userInfo,
    });
  });
});

server.listen(8000, () => {
  console.log("server is up and running on port 8000");
});
